package com.wnxy.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wnxy.admin.common.handler.Asserts;
import com.wnxy.admin.common.handler.BusinessEnum;
import com.wnxy.admin.common.util.AliOssUtil;
import com.wnxy.admin.dto.MaintenanceTaskDto;
import com.wnxy.admin.dto.PageResult;
import com.wnxy.admin.entity.AlarmMessages;
import com.wnxy.admin.entity.MaintenancePersonnel;
import com.wnxy.admin.entity.MaintenanceTasks;
import com.wnxy.admin.entity.TaskImages;
import com.wnxy.admin.mapper.AlarmMessagesMapper;
import com.wnxy.admin.mapper.MaintenancePersonnelMapper;
import com.wnxy.admin.mapper.MaintenanceTasksMapper;
import com.wnxy.admin.mapper.TaskImagesMapper;
import com.wnxy.admin.service.IMaintenanceTasksService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wnxy.admin.vo.AlertEnum;
import com.wnxy.admin.vo.TaskVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author All
 * @since 2023-11-29
 */
@Service
@RequiredArgsConstructor
public class MaintenanceTasksServiceImpl extends ServiceImpl<MaintenanceTasksMapper, MaintenanceTasks> implements IMaintenanceTasksService {

    private final MaintenanceTasksMapper maintenanceTasksMapper;
    private final MaintenancePersonnelMapper maintenancePersonnelMapper;
    private final TaskImagesMapper taskImagesMapper;
    private final AlarmMessagesMapper alarmMessagesMapper;
    private final AliOssUtil aliOssUtil;


    @Override
    public PageResult queryAlarmTask(MaintenanceTaskDto maintenanceTaskDto) {
        Page page = Page.of(maintenanceTaskDto.getPageNum(), maintenanceTaskDto.getPageSize());

        //根据任务的名称/任务类型 进行匹配
        Page result = maintenanceTasksMapper.selectPage(page, Wrappers.lambdaQuery(MaintenanceTasks.class)
                .like(!StringUtils.isEmpty(maintenanceTaskDto.getTaskName()), MaintenanceTasks::getTaskName, maintenanceTaskDto.getTaskName())
                .like(!StringUtils.isEmpty(maintenanceTaskDto.getTaskType()), MaintenanceTasks::getTaskType, maintenanceTaskDto.getTaskType())
                .eq(MaintenanceTasks::getFlag, 0));

        return new PageResult<>(result.getTotal(), result.getRecords());
    }

    @Override
    @Transactional
    public void editMaintenanceTask(MaintenanceTasks maintenanceTasks) {
        //任务状态不是处理中无法编辑(只能编辑运维人员)
        Asserts.fail(maintenanceTasks.getStatus() != -1, BusinessEnum.TASK_IS_NOT_BEING_PROCESSED);

        //根据任务id查询任务
        MaintenanceTasks dbMaintenanceTask = maintenanceTasksMapper.selectById(maintenanceTasks.getTaskId());
        //判断运维人员是否被更改
        if(!ObjectUtils.isEmpty(dbMaintenanceTask) && maintenanceTasks.getTaskOperatorId().equals(dbMaintenanceTask.getTaskOperatorId())) {
            //此处判断出提交对象未作任何更改
            return;
        }

        //修改初始的运维人员的状态 /从维修中更改为空闲中
        MaintenancePersonnel dbOperator = maintenancePersonnelMapper.selectById(dbMaintenanceTask.getTaskOperatorId());
        dbOperator.setStatus(2);
        maintenancePersonnelMapper.updateById(dbOperator);

        //修改更改后的运维人员状态 /从空闲中改为维修中
        MaintenancePersonnel personnel = maintenancePersonnelMapper.selectById(maintenanceTasks.getTaskOperatorId());
        personnel.setStatus(-1);
        maintenancePersonnelMapper.updateById(personnel);

        //修改任务信息
        maintenanceTasksMapper.updateById(maintenanceTasks);
    }

    @Override
    @Transactional
    public void removeBatchMaintenanceTask(List<Long> maintenanceTaskIds) {
        //遍历id集合,查询任务
        List<MaintenanceTasks> maintenanceTasks = maintenanceTasksMapper.selectBatchIds(maintenanceTaskIds);

        //遍历任务集合,删除状态为已处理的任务(逻辑删除)
        maintenanceTasks.forEach(e -> {
            Asserts.fail(e.getStatus() != 1, BusinessEnum.TASK_NOT_COMPLETED);
            e.setFlag(e.getTaskId().intValue());
            maintenanceTasksMapper.updateById(e);

            //删除任务对应的图片集合
            List<TaskImages> taskImages = taskImagesMapper.selectList(Wrappers.lambdaQuery(TaskImages.class)
                    .eq(TaskImages::getTaskNumber, e.getTaskId()));
            taskImages.forEach(j -> {
                j.setFlag(j.getImageId().intValue());
                taskImagesMapper.updateById(j);

                //从oss储存库中清理图片信息
                aliOssUtil.deleteImg(j.getImagePath());
            });
        });
    }

    @Override
    @Transactional
    public void processingTasks(MaintenanceTasks maintenanceTasks) {
        //只有处理中的任务可以提交处理请求
        Asserts.fail(maintenanceTasks.getStatus() != -1, BusinessEnum.TASK_IS_NOT_BEING_PROCESSED);

        Asserts.fail(ObjectUtils.isEmpty(maintenanceTasks.getEndTime()), BusinessEnum.END_DATE_NOT_UPLOADED);

        Asserts.fail(maintenanceTasks.getStartTime().after(maintenanceTasks.getEndTime()), BusinessEnum.TIME_ERROR);

        //根据任务id查询图片表,判断是否上传处理图片
        List<TaskImages> taskImages = taskImagesMapper.selectList(Wrappers.lambdaQuery(TaskImages.class)
                .eq(TaskImages::getTaskNumber, maintenanceTasks.getTaskId()));

        //判断集合是否为空 图片检测失败
        Asserts.fail(taskImages.isEmpty(), BusinessEnum.IMAGE_DETECTION_ANOMALY);

        //修改任务状态 /已处理
        maintenanceTasks.setStatus(1);
        maintenanceTasks.setEndTime(new Date());
        maintenanceTasksMapper.updateById(maintenanceTasks);

        //修改报警消息的状态 /已处理
        AlarmMessages alarmMessages = alarmMessagesMapper.selectById(maintenanceTasks.getTaskAlarmId());
        alarmMessages.setStatus(1);
        alarmMessagesMapper.updateById(alarmMessages);

        //修改运维人员状态 /空闲
        MaintenancePersonnel dbOperator = maintenancePersonnelMapper.selectById(maintenanceTasks.getTaskOperatorId());
        dbOperator.setStatus(2);
        maintenancePersonnelMapper.updateById(dbOperator);

        //发送处理结果消息给充电桩 TODO
    }

    @Override
    @Transactional
    public void ReturnTask(MaintenanceTasks maintenanceTasks) {
        //判断任务等级/类型 只能退回未处理的一般任务
        Asserts.fail(maintenanceTasks.getStatus() != 0, BusinessEnum.THE_TASK_HAS_BEEN_PROCESSED);
        Asserts.fail(!maintenanceTasks.getTaskType().equals(AlertEnum.Maintenance_tasks.getMsg()), BusinessEnum.RISK_LEVEL_IS_TOO_HIGH);

        //删除任务
        maintenanceTasksMapper.deleteById(maintenanceTasks);
    }

    @Override
    public TaskVo viewTask(MaintenanceTasks maintenanceTasks) {
        TaskVo taskVo = new TaskVo();
        taskVo.setTaskName(maintenanceTasks.getTaskName());

        //查询运维人员信息
        if(!ObjectUtils.isEmpty(maintenanceTasks.getTaskOperatorId())) {
            MaintenancePersonnel personnel = maintenancePersonnelMapper.selectById(maintenanceTasks.getTaskOperatorId());

            taskVo.setUserName(personnel.getUserName());
            taskVo.setUserNumber(personnel.getUserNumber());
        }

        return taskVo;
    }
}
